import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/store/user'
import { convertMenusToRoutes } from '@/utils/menu-utils'
import abc from '@/components/AuroraBackground.vue'

const constantRoutes = [
  {
    path: '/',
    name: 'login',
    component: () => import('@/views/login/index.vue')
  }, {
    path: '/background', 
    name: 'background',
    component: abc
    
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: constantRoutes
})

// 路由白名单（不需要登录就能访问的页面）
const whiteList = ['/']

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()

  const token = userStore.token

  // 🚫 没有 token 且不在白名单内，跳回登录页
  if (!token && !whiteList.includes(to.path)) {
    return next('/')
  }

  // ✅ 有 token 且没添加动态路由时
  if (token && !userStore.dynamicRoutesAdded) {
    try {
      // 如果用户信息为空就拉一次用户数据
      if (!userStore.userInfo.menus || userStore.userInfo.menus.length === 0) {
        await userStore.fetchUserInfo()
      }

      const asyncRoutes = convertMenusToRoutes(userStore.userInfo.menus)
      asyncRoutes.forEach(route => {
        router.addRoute(route)
      })

      userStore.dynamicRoutesAdded = true

      // ⚠️ 确保当前路由重新走一次匹配逻辑
      return next({ ...to, replace: true })
    } catch (err) {
      console.error('路由守卫获取用户信息失败:', err)
      userStore.reset() // 清空token等
      return next('/')
    }
  }

  next()
})

export default router
